package com.eurasia.assignment.service;

import com.eurasia.assignment.domain.Project;
import com.eurasia.assignment.domain.ProjectAssignment;
import com.eurasia.assignment.infrastructure.entity.ProjectAssignmentEntity;
import com.eurasia.assignment.infrastructure.entity.ProjectEntity;
import com.eurasia.assignment.infrastructure.repository.ProjectAssignmentRepository;
import com.eurasia.assignment.infrastructure.repository.ProjectRepository;
import com.eurasia.assignment.service.port.in.CreateProjectAssignmentUseCase;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class CreateProjectAssignmentService implements CreateProjectAssignmentUseCase {
    private final ProjectRepository projectRepository;
    private final ProjectAssignmentRepository projectAssignmentRepository;
    
    @Override
    @Transactional
    public void createProjectAssignment(CreateProjectAssignmentCommand command) {
        // 根据id获取Project
        Project project = projectRepository.findById(command.projectId())
                .orElseThrow(() -> new ProjectNotFoundException(command.projectId()))
                .toDomain();

        // 创建项目分配
        ProjectAssignment assignment = project.createAssignment(command.teamLeadId(), command.teamMemberIds());
        
        // 保存项目分配
        projectRepository.save(ProjectEntity.fromDomain(project));
        projectAssignmentRepository.save(ProjectAssignmentEntity.fromDomain(assignment));
    }
    
    public static class ProjectNotFoundException extends RuntimeException {
        public ProjectNotFoundException(Long projectId) {
            super("项目不存在: " + projectId);
        }
    }
}
